package com.yy.job.core.run.flow;

import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.CollectionUtils;

import com.yy.job.common.enums.ErrorCodeEnum;
import com.yy.job.common.enums.JobStatusEnum;
import com.yy.job.common.enums.JobStepStatusEnum;
import com.yy.job.core.domain.JobStepDomain;
import com.yy.job.core.domain.context.JobContext;
import com.yy.job.core.domain.context.JobStepContext;
import com.yy.job.spring.YYSpringBeanUtils;
import com.yy.job.utils.exception.YYJobRuntimeExceptionUtils;

public class JobStepsRunFlow extends AbsJobRunFlow<JobContext> {
	
	private Logger log = LoggerFactory.getLogger(JobStepsRunFlow.class);
	
	@Override
	protected boolean idempotent(JobContext jobContext) {
		return false;
	}
	
	@Override
	protected void check(JobContext jobContext) {
		// 查询步骤列表并校验
		List<JobStepDomain> jobSteps = YYSpringBeanUtils.getJobStepDomainService().listJobStepByJobId(jobContext.getJobDomain().getId());
		log.debug("Job Worker handle jobSteps, query jobSteps={}", JobStepDomain.taskListToString(jobSteps));
		if (CollectionUtils.isEmpty(jobSteps)) {
			YYJobRuntimeExceptionUtils.throwException(ErrorCodeEnum.CHECK_STEP_NOT_EMPTY, "stepData is empty");
		}
		jobContext.getJobDomain().setJobStepDomains(jobSteps);
	}

	@Override
	protected void prepare(JobContext jobContext) {
		
	}

	@Override
	protected void run(JobContext jobContext) {
		// 依次执行步骤
		for (JobStepDomain jobStepDomain : jobContext.getJobDomain().getJobStepDomains()) {
			// 已经成功或者跳过的，不再重新执行
			if (jobStepDomain == null 
				|| jobStepDomain.getStepStatus() == JobStepStatusEnum.SUCCESS
				|| jobStepDomain.getStepStatus() == JobStepStatusEnum.SKIP) {
				continue;
			}
			
			// 执行步骤
			JobStepContext jobStepContext = new JobStepContext(jobContext, jobStepDomain, jobContext.getOperator());
			JobStepRunFlow jobStepRunFlow = new JobStepRunFlow();
			jobStepRunFlow.flow(jobStepContext);
			
			// 只要有1个失败，就跳出
			if(!jobStepContext.getJobResult().isSuccess()) {
				jobContext.setFinalJobStatus(JobStatusEnum.FAIL);
				break;
			} 
		}
	}

	@Override
	protected void after(JobContext jobContext) {
		
	}
	
	@Override
	protected void exception(JobContext jobContext, Exception e) {
		
	}
	
	@Override
	protected void end(JobContext jobContext) {
		
	}

}
